package com.self.smallma.myblogweb.web;


import com.self.smallma.myblogweb.common.utils.R;
import com.self.smallma.myblogweb.component.SmsComponent;
import com.self.smallma.myblogweb.util.HttpUtils;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController

public class SmsController {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    SmsComponent smsComponent;
    @PostMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone){
        //发送的验证码   sms:code 前缀


        // 1.接口防刷
        //2.验证码的再次校验----存入redis
        String redisCode = redisTemplate.opsForValue().get("sms:code" + phone);
        if (!StringUtils.isEmpty(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis()-l <60000){
                //60s内不能再发
                return R.error("验证码提交频率过高");
            }
        }

//        String  code = Math.round(Math.random() * 1000000)+"_"+System.currentTimeMillis();
        String  code = Math.round(Math.random() * 1000000)+"_"+System.currentTimeMillis();

        //2.验证码的再次校验----存入redis
        //redis缓存验证码，五分钟有效，防止同一个手机号在60s内重复发送验证码
        redisTemplate.opsForValue().set("sms:code"+phone,code,5, TimeUnit.MINUTES);
        smsComponent.sendSmsCode(phone,Long.parseLong(code.split("_")[0]));
        return R.ok();
    }


}
